package com.springboot.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {

    private String host;

    private String port;

    private String pool;

    @Value("${elasticsearch.cluster.name}")
    private String clusterName;



    @Bean
    public TransportClient transportClient() throws UnknownHostException {

        Settings settings = Settings.builder()
                //集群名字
                .put("cluster.name", clusterName)
                //增加嗅探机制，找到ES集群
                .put("client.transport.sniff", true)
                //增加线程池个数，暂时设为5
                .put("thread_pool.search.size", Integer.parseInt(pool))
                .build();


        PreBuiltTransportClient transportClient = new PreBuiltTransportClient(settings);

        InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(host), Integer.valueOf(port));

        transportClient.addTransportAddress(address);

        return transportClient;
    }



    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getPool() {
        return pool;
    }

    public void setPool(String pool) {
        this.pool = pool;
    }
}
